// init
package model

import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"time"

	"git.oschina.net/unphp/go-utils/base"
	"git.oschina.net/unphp/go-utils/log"
	"git.oschina.net/unphp/goweb/utils"
)

// 批量定义全局变量
var (
	RunMode              string
	ConfData             *utils.Conf //配置
	Log                  *log.Log    //日志
	RootPath             string      //根目录
	ServerDeferFuncSlice []func()    //服务销毁前的回调函数
)

func init() {

	//初始化ServerDeferFuncSlice
	ServerDeferFuncSlice = make([]func(), 0)

	//服务的根目录（绝对路径）
	RootPath = base.RootPath()

	//默认的配置文件路径
	defaultConfFile := RootPath + "/conf/conf.ini"
	configfile := flag.String("conf", defaultConfFile, "The conf of path")

	//默认的启动模式
	defaultRunMode := "api"
	runMode := flag.String("mode", defaultRunMode, "The mode of server's run")
	flag.Parse()

	//设置配置文件路径
	if initconf, err := utils.ParseFile(*configfile); err != nil {
		panic("conf.ini can't open")
	} else {
		ConfData = &utils.Conf{
			Initconf: initconf,
		}
	}

	//设置启动模式
	RunMode = *runMode

	//系统日志
	Log = log.New()

}

//监听服务运行状态，记录服务日志。
func Listen() {
	logpath := RootPath + "/" + ConfData.Get("core", "logpath").String()
	oldStr := time.Now().Format("2006-01-02")
	files := openLogFile(logpath, oldStr)
	var logwriter *bufio.Writer
	logwriter = bufio.NewWriter(files)
	logwriter.WriteString("-------------------服务开始启动--------------------" + "\r\n")
	logwriter.WriteString("Date:" + time.Now().Format("2006-01-02 15:04:05") + "\r\n")
	logwriter.Flush()
	for {
		nowStr := time.Now().Format("2006-01-02")
		if nowStr != oldStr {
			oldStr = nowStr
			files.Close()
			files = openLogFile(logpath, nowStr)
			logwriter = bufio.NewWriter(files)
		}
		select {
		case msg := <-Log.ChanLogMsg:
			for _, v := range msg {
				fmt.Println(v)
				logwriter.WriteString(v + "\r\n")
			}
			logwriter.Flush()
		default:
		}
		time.Sleep(1 * time.Second)
	}
}

func DeferFunc() {
	for _, fun := range ServerDeferFuncSlice {
		fun()
	}
}

func openLogFile(logpath, n string) *os.File {
	logPath := logpath + "/syslog"
	os.MkdirAll(logPath, 0755)
	files, _ := os.OpenFile(logPath+"/"+n, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	return files
}
